import copy
import time

import torch
import torchvision
from torch.optim.lr_scheduler import StepLR

from safebooru.dataset import CHEWANbooru
from safebooru.config import *
from tqdm import tqdm
print("PyTorch Version: ", torch.__version__)
print("Torchvision Version: ", torchvision.__version__)

"""datasets"""
image_datasets = {
    'train': CHEWANbooru(train=True, transform=data_transforms["train"]),
    'val': CHEWANbooru(train=False, transform=data_transforms["val"])}
# trainset = CHEWAN(root_dir="./",train=True,transform=transform)
"""dataloaders"""
dataloaders_dict = {x: torch.utils.data.DataLoader(
    image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=4) for x in ['train', 'val']}


def train_model(model, dataloaders, criterion, optimizer, num_epochs=20):
    since = time.time()

    val_acc_history = []

    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0
    scheduler = StepLR(optimizer, step_size=1, gamma=0.8)
    for epoch in range(num_epochs):
        print('Epoch {}/{}'.format(epoch, num_epochs - 1))
        print('-' * 10)

        # Each epoch has a training and validation phase
        for phase in ['train', 'val']:
            if phase == 'train':
                model.train()  # Set model to training mode
            else:
                model.eval()   # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            for iter, (inputs, labels) in enumerate(tqdm(dataloaders[phase])):
                inputs = inputs.to(device)
                labels = labels.to(device)

                # zero the parameter gradients
                optimizer.zero_grad()

                # forward
                # track history if only in train
                with torch.set_grad_enabled(phase == 'train'):
                    # Get model outputs and calculate loss
                    # Special case for inception because in training it has an auxiliary output. In train
                    #   mode we calculate the loss by summing the final output and the auxiliary output
                    #   but in testing we only consider the final output.
                    outputs, kl_loss = model(inputs)
                    assert not torch.any(torch.isnan(outputs))
                    loss = criterion(outputs, labels)

                    _, preds = torch.max(outputs, 1)

                    # backward + optimize only if in training phase
                    if phase == 'train':
                        kl_loss = torch.stack(kl_loss).mean()
                        (loss + kl_loss * 0.5).backward()
                        optimizer.step()

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)
                # print("iter: {: 6d} acc:{:.4f}".format(iter, running_corrects * 1.0 / ((iter + 1) * inputs.size(0))), end='\r')

            epoch_loss = running_loss / len(dataloaders[phase].dataset)
            epoch_acc = running_corrects.double(
            ) / len(dataloaders[phase].dataset)

            print('{} Loss: {:.4f} Acc: {:.4f}'.format(
                phase, epoch_loss, epoch_acc))

            # deep copy the model
            if phase == 'val' and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())
            if phase == 'val':
                val_acc_history.append(epoch_acc)

        print()
        torch.save(model.state_dict(), "model.pt")
        scheduler.step()

    time_elapsed = time.time() - since
    print('Training complete in {:.0f}m {:.0f}s'.format(
        time_elapsed // 60, time_elapsed % 60))
    print('Best val Acc: {:4f}'.format(best_acc))

    # load best model weights
    model.load_state_dict(best_model_wts)
    return model, val_acc_history


if __name__ == "__main__":
    # while True:
    #     pass
    model_ft, hist = train_model(
        resnet50, dataloaders_dict, criterion, optimizer_ft)
